<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="货物" prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="请输入货物名称" clearable style="width: 240px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
      </el-row>
  
      <el-table v-loading="loading" :data="salesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户名称" align="center" prop="customerName">
          <template slot-scope="scope">
            <el-input v-if="scope.row.editing" v-model="scope.row.customerName" placeholder="请输入客户名称" />
            <span v-else>{{ scope.row.customerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="货物" align="center" prop="goodsName">
          <template slot-scope="scope">
            <el-input v-if="scope.row.editing" v-model="scope.row.goodsName" placeholder="请输入货物名称" />
            <span v-else>{{ scope.row.goodsName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity">
          <template slot-scope="scope">
            <el-input-number 
              v-if="scope.row.editing" 
              v-model="scope.row.quantity" 
              :min="1" 
              @change="calculateTotal(scope.row)" 
            />
            <span v-else>{{ scope.row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="unitPrice">
          <template slot-scope="scope">
            <el-input-number 
              v-if="scope.row.editing" 
              v-model="scope.row.unitPrice" 
              :min="0" 
              :precision="2" 
              @change="calculateTotal(scope.row)" 
            />
            <span v-else>{{ scope.row.unitPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总价" align="center" prop="totalPrice">
          <template slot-scope="scope">
            <span>{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="额外成本" align="center" prop="extraCost">
          <template slot-scope="scope">
            <el-input-number 
              v-if="scope.row.editing" 
              v-model="scope.row.extraCost" 
              :min="0" 
              :precision="2" 
            />
            <span v-else>{{ scope.row.extraCost }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订货时间" align="center" prop="orderTime" width="180">
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.editing"
              v-model="scope.row.orderTime"
              type="datetime"
              placeholder="选择订货时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
            <span v-else>{{ parseTime(scope.row.orderTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="送货时间" align="center" prop="deliveryTime" width="180">
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.editing"
              v-model="scope.row.deliveryTime"
              type="datetime"
              placeholder="选择送货时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
            <span v-else>{{ parseTime(scope.row.deliveryTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template slot-scope="scope">
            <template v-if="scope.row.editing">
              <el-button size="mini" type="text" icon="el-icon-check" @click="handleSave(scope.row)">保存</el-button>
              <el-button size="mini" type="text" icon="el-icon-close" @click="cancelEdit(scope.row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
  </template>
  
  <script>
  import { parseTime } from "@/utils/ruoyi";
  import { listSales, getSales, delSales, addSales, updateSales } from "@/api/system/sales";
  
  export default {
    name: "Sales",
    data() {
      return {
        loading: false,
        ids: [],
        multiple: true,
        showSearch: true,
        total: 0,
        salesList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          customerName: undefined,
          goodsName: undefined
        },
        editingRow: null
      };
    },
    created() {
      this.getList();
    },
    methods: {
      getList() {
        this.loading = true;
        listSales(this.queryParams).then(response => {
          this.salesList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleAdd() {
        const newRow = {
          saleId: undefined,
          customerName: "",
          goodsName: "",
          quantity: 1,
          unitPrice: 0,
          totalPrice: 0,
          extraCost: 0,
          orderTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
          deliveryTime: "",
          editing: true
        };
        this.salesList.unshift(newRow);
        this.editingRow = newRow;
      },
      handleEdit(row) {
        if (this.editingRow) {
          this.cancelEdit(this.editingRow);
        }
        row.editing = true;
        this.editingRow = row;
      },
      cancelEdit(row) {
        if (!row.saleId) {
          // 如果是新增行但未保存，直接移除
          const index = this.salesList.indexOf(row);
          if (index > -1) {
            this.salesList.splice(index, 1);
          }
        } else {
          row.editing = false;
        }
        this.editingRow = null;
      },
      handleSave(row) {
        // 简单验证
        if (!row.customerName || !row.goodsName || row.quantity <= 0 || row.unitPrice <= 0) {
          this.$message.error("请填写完整信息且数量和单价必须大于0");
          return;
        }
  
        const action = row.saleId ? updateSale : addSale;
        action(row).then(() => {
          this.$modal.msgSuccess(row.saleId ? "修改成功" : "新增成功");
          row.editing = false;
          this.editingRow = null;
          // 如果是新增，刷新列表获取完整数据
          if (!row.saleId) {
            this.getList();
          }
        });
      },
      calculateTotal(row) {
        if (row.quantity && row.unitPrice) {
          row.totalPrice = (row.quantity * row.unitPrice).toFixed(2);
        } else {
          row.totalPrice = 0;
        }
      },
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.saleId);
        this.multiple = selection.length === 0;
      },
      handleDelete(row) {
        const saleIds = row.saleId || this.ids;
        this.$modal.confirm("是否确认删除选中的销售记录？").then(() => {
          return delSale(saleIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
      }
    }
  };
  </script>
  
  <style scoped>
  .el-input-number {
    width: 120px;
  }
  </style>